package com.xjoyt.pay.master.dao.impl;

import java.util.ArrayList;
import java.util.List;

import javax.persistence.criteria.Predicate;

import org.apache.commons.collections.CollectionUtils;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.Pageable;
import org.springframework.data.jpa.domain.Specification;

import com.xjoyt.pay.abstracts.AbstractDao;
import com.xjoyt.pay.dto.PageParam;
import com.xjoyt.pay.dto.PageResult;
import com.xjoyt.pay.master.dao.MerchantChannelRepositoryCustom;
import com.xjoyt.pay.master.params.MerchantChannelPageParam;
import com.xjoyt.pay.master.po.MerchantChannel;
import com.xjoyt.pay.master.repository.MerchantChannelRepository;

public class MerchantChannelRepositoryImpl extends AbstractDao implements MerchantChannelRepositoryCustom {

	@Autowired
	private MerchantChannelRepository repository;

	@Override
	public PageResult<MerchantChannel> loadPage(PageParam<MerchantChannelPageParam> param) {

		Pageable pageable = getPageable(param);
		Specification<MerchantChannel> spec = getSpecification(param.query);
		Page<MerchantChannel> pageResult = repository.findAll(spec, pageable);
		return new PageResult<MerchantChannel>(pageResult.getTotalElements(), pageResult.getContent());
	}

	private Specification<MerchantChannel> getSpecification(MerchantChannelPageParam param) {
		Specification<MerchantChannel> spec = (root, query, cb) -> {
			List<Predicate> list = new ArrayList<>();
			if (StringUtils.isNotBlank(param.merchantId))
				list.add(cb.equal(root.get("merchant").get("id"), param.merchantId));
			if (StringUtils.isNotBlank(param.query)) {
				for (String string : param.query.split(" ")) {
					if (StringUtils.isBlank(string))
						continue;
					String like = "%" + string + "%";
					list.add(cb.or(cb.like(root.get("channel").get("name"), like), cb.like(root.get("no"), like),
							cb.like(root.get("key"), like)));
				}
			}
			if (param.enabled != null) {
				list.add(cb.equal(root.get("enabled"), param.enabled));
			}
			if (CollectionUtils.isNotEmpty(list))
				query.where(cb.and(list.toArray(new Predicate[list.size()])));

			return null;
		};
		return spec;
	}

	@Override
	public MerchantChannel findOneByMerchantIdAndChannelIdAndEnabledTrue(String merchantId, String channelId) {
		Page<MerchantChannel> page = repository.findAllByMerchantIdAndChannelIdAndEnabledTrue(merchantId, channelId,
				getFirstPageable());
		return page.hasContent() ? page.iterator().next() : null;
	}

}
